from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone


class UserManager(BaseUserManager):
    """自定义用户管理器"""

    def create_user(self, phone, email=None, password=None, **extra_fields):
        """创建普通用户"""
        if not phone:
            raise ValueError('手机号必须填写')

        user = self.model(
            phone=phone,
            email=email,
            **extra_fields
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, phone, email=None, password=None, **extra_fields):
        """创建超级用户"""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(phone, email, password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    """自定义用户模型"""
    last_login = models.DateTimeField(blank=True, null=True, verbose_name='最后登录时间')
    username = models.CharField(max_length=150, blank=True, null=True, verbose_name='用户名')
    phone = models.CharField(max_length=15, unique=True, verbose_name='手机号')
    email = models.EmailField(max_length=254, blank=True, null=True, verbose_name='邮箱')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    is_staff = models.BooleanField(default=False, verbose_name='是否员工')
    is_superuser = models.BooleanField(default=False, verbose_name='是否超级用户')

    avatar = models.ImageField(
        upload_to='avatars/%Y/%m',
        null=True,
        blank=True,
        verbose_name='头像'
    )

    objects = UserManager()

    USERNAME_FIELD = 'phone'  # 使用手机号作为登录字段
    REQUIRED_FIELDS = ['email']  # 创建超级用户时的必填字段

    def __str__(self):
        return self.phone

    @property
    def is_anonymous(self):
        """
        判断是否是匿名用户
        """
        return False

    @property
    def is_authenticated(self):
        """
        判断是否已认证
        """
        return True

    def get_full_name(self):
        """
        返回用户全名
        """
        return self.username or self.phone

    def get_short_name(self):
        """
        返回用户简称
        """
        return self.username or self.phone[:3] + '****' + self.phone[-4:]

    def has_perm(self, perm, obj=None):
        """
        判断用户是否有特定权限
        """
        return self.is_staff

    def has_module_perms(self, app_label):
        """
        判断用户是否有访问特定应用的权限
        """
        return self.is_staff

    class Meta:
        db_table = 'user'
        verbose_name = '用户'
        verbose_name_plural = '用户'
        ordering = ['-created_at']  # 添加默认排序


class SMSLog(models.Model):
    """短信发送日志"""
    phone_number = models.CharField(max_length=11, verbose_name='手机号')
    send_status = models.BooleanField(default=False, verbose_name='发送状态')
    message_id = models.CharField(max_length=64, verbose_name='消息ID')
    response_code = models.CharField(max_length=32, verbose_name='响应码')
    response_message = models.TextField(null=True, blank=True, verbose_name='响应消息')
    send_at = models.DateTimeField(default=timezone.now, verbose_name='发送时间')

    class Meta:
        db_table = 'sms_log'
        verbose_name = '短息发送日志'
        verbose_name_plural = '短信发送日志'
